package com.vooda.service.impl;

import com.vooda.dao.TicketDao;
import com.vooda.dao.UserTicketDao;
import com.vooda.entity.Ticket;
import com.vooda.entity.UserTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * @author KennyDavid
 */

@Slf4j
@Service
public class RefreshImpl {

    private TicketDao ticketDao;
    private UserTicketDao userTicketDao;

    public RefreshImpl(TicketDao ticketDao, UserTicketDao userTicketDao) {
        this.ticketDao = ticketDao;
        this.userTicketDao = userTicketDao;
    }

    @Scheduled(cron = "0 0 0 * * ? ")
    @Transactional(rollbackOn = Exception.class)
    public void refreshTicket() {
        List<UserTicket> list = userTicketDao.findAllByStatus(1);
        for (UserTicket userTicket : list) {
            Ticket ticket = ticketDao.findOne(userTicket.getTicketId());
            if (!ObjectUtils.isEmpty(ticket)) {
                if (!ticket.getIsForever()) {
                    if (ticket.getEndTime().getTime() < System.currentTimeMillis()) {
                        userTicket.setStatus(3);
                        userTicketDao.saveAndFlush(userTicket);
                    }
                }
            }
        }
    }
}
